package com.example.shiroredis.utils.sdk;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.example.shiroredis.utils.GetDate;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: hwz
 * @Date: 2018/8/15
 */
@Slf4j
public class AlipayUtil {

    public static final String APP_ID = "2019010762812465";
    public static final String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCeW5vMwQx4eTMTOIIiK6NKGzSBL/uBgSo4jRc1L1l8rwc5KK0vUPqAIuFf7cQ2Uy/k+NkihJOAO92fT5AiVjr3UBE9Wep+sAkDLQEu7m5N3xsprrJeOvkW6lw+NYhcj5Jyo75N/pxaHePC9XnoyoS9/m7T77Ex93jktvgkRhmoL238smAXoUT39Ak75Ab5bgeNaBTfNmmdw9dy7iSEFgEdMSTNzR0Znf+EUNVuPmgPH4bd2tz9iSL5jLvteGPMuCyln6bWfRgPw5JVXY3PAncflQAO9H472J+R6dMcimCjNgZAElTnrhtBso/JwAh5Q3h1flCvIhOvzaw7EhXqh9XZAgMBAAECggEAB3xZHxK5HjDMg0oWjLr3WxdyIfE8uGB8uHOi9zanykcT1lXf6e6wCMKdWMWKku7XwsEosoMF3ff2gANo0ta0ruAwEHBhr19u7aGA/tDykefMBuplMCMl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public static final String CHARSET = "utf-8";
    public static final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkAL5nCHRFMJt1nf3UiU6BAyA/+VHs1DnK56oQ8GHbZFqEOoHHNJvdS+stH8SANjdXDbMl0qGABWyR2XOrHEr/NJGzCyqyXv18WFXbourn0KkjhRX/pcogI91taak556AjgC4VQeI3hMaDmsdHrS4U+S4G1VtoJCWB0bUqo37RSIlOzW4VwIRWwEeXNaA6E02V64zSFTHpFVWtogD38fuN0uk/F4JpPYEBE0j2OfBvZYSF6TMZz2XQz9rfyWf4yOirR30zWr5hkCkUq8KGQ5Clna6ePlTI5G+GHccLpaMCb2ZRbMieiuTPxMnQTzJhFpF3Sjkn6NIvb1a48cyE8PslwIDAQAB";
    public static final String TRADE_SUCCESS = "TRADE_SUCCESS";


    //实例化客户端
    public static AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2");

    public static String pay(String body,String subject,String outTradeNo,String totalAmount) {
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(body);
        model.setSubject(subject);
        model.setOutTradeNo(outTradeNo);
        model.setTimeoutExpress("30m");
        model.setTotalAmount(totalAmount);
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl("http://xiangcheng.fanyin1036.com/webapi/"+ "/mall/app/pay/data/aliNotify");
            try {
                //这里和普通的接口调用不同，使用的是sdkExecute
                AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
                return response.getBody();
            } catch (AlipayApiException e) {
                log.info("支付宝支付异常",e);
        }
        return "failure";
    }
    public static String  payFKPT(String body, String subject, String outTradeNo, String totalAmount, HttpServletResponse httpResponse) throws IOException {
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
        alipayRequest.setReturnUrl("http://localhost:80/api/pc/returnTest");
        //花生壳
        //alipayRequest.setNotifyUrl("http://198s2a4752.iask.in/api/aliNotify");//在公共参数中设置回跳和通知地址
        //TODO 线上会掉地址
        alipayRequest.setNotifyUrl(/*Constants.URL + */"/api/aliNotify");//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                //设置订单号
                "    \"out_trade_no\":\""+outTradeNo+"\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                //TODO 设置金额
                //"    \"total_amount\":0.01," +
                "    \"total_amount\":"+totalAmount+"," +
                "    \"subject\":\""+subject+"\"," +
                "    \"body\":\""+body+"\"," +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\"2088511833207846\"" +
                "    }"+
                "  }");//填充业务参数
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        return form;
        //httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        //httpResponse.getWriter().flush();
        //httpResponse.getWriter().close();

    }

    public static void notify(HttpServletRequest request,
                              HttpServletResponse response){
        //获取支付宝POST过来反馈信息
        Map<String,String> params = getRequestParams(request);
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        try {
            PrintWriter writer = response.getWriter();
            boolean flag = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, "RSA2");
            if (flag) {
                // 按照支付结果异步通知中的描述，对支付结果中的业务内容进行1\2\3\4二次校验，校验成功后在response中返回success，校验失败返回failure
                String out_trade_no = params.get("out_trade_no");
                String total_amount = params.get("total_amount");
                if (TRADE_SUCCESS.equals(params.get("trade_status"))
                        && APP_ID.equals(params.get("app_id"))) {



                    log.info("支付宝异步通知成功");
                    writer.write("success");
                } else {
                    log.info("支付宝异步通知失败");
                    writer.write("failure");
                }
            } else {
                log.info("支付宝异步通知失败");
                writer.write("failure");
            }
        }catch (Exception e){
            log.info("支付宝异步回调异常",e);
        }
    }

    /**
     * 退款
     */
    public static void refuseOrder(String orderNumber,Double account) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",APP_ID,APP_PRIVATE_KEY,"json",CHARSET,ALIPAY_PUBLIC_KEY,"RSA2");
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        //与预授权转支付商户订单号相同，代表对该笔交易退款
        model.setOutTradeNo(orderNumber);
        //退款金额
        model.setRefundAmount(account+"");
        //退款原因
        model.setRefundReason("订单退款");
        //退款单号
        model.setOutRequestNo(GetDate.getProductNumber(new Date()));
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizModel(model);
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        //响应json数据
        String responseJson = response.getBody();
        //解析数据，封装json
        JSONObject responseJsonObject = JSONObject.parseObject(responseJson);
        //AliRefundOrderVo orderVo = new AliRefundOrderVo();
        ////封装result
        //String result = responseJsonObject.getString("alipay_trade_refund_response");
        //orderVo = JSONObject.parseObject(result, AliRefundOrderVo.class);
        //return orderVo;
    }

    public static Map<String, String> getRequestParams(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration<String> e = request.getParameterNames();
        while (e.hasMoreElements()) {
            String name = e.nextElement();
            String value = request.getParameter(name);
            map.put(name, value);
        }
        return map;
    }
}
